//
//  HoursToChooseManger.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2020/5/31.
//  Copyright © 2020 杨东宝. All rights reserved.
//

import UIKit
class AlertManger: NSObject {
    //MARK:-时间显示：hh:mm
    static func showHHMMtime(title:String) -> BRDatePickerView {
        
        let  datePickerView = BRDatePickerView()
        datePickerView.pickerMode = .time;
        datePickerView.title = title;
        //datePickerView.selectDate = self.birthtimeSelectDate;
        datePickerView.isShowAMAndPM = true;
        
        //MARK:-自定义弹框样式
        let customStyle = BRPickerStyle()
        customStyle.titleTextColor = hexColor(0x000000,0xBBBBBB)
        customStyle.titleTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneBorderStyle = .none
        customStyle.cancelBorderStyle = .none
        datePickerView.pickerStyle = customStyle;
        return datePickerView
    }
    //MARK:-性别选择
    static func showSex() -> BRStringPickerView {
        
        let  stringPickerView = BRStringPickerView()
        stringPickerView.pickerMode = .componentSingle
        stringPickerView.title = "请选择性别";
        stringPickerView.dataSourceArr = ["男","女"];
        // 自定义弹框样式
        let customStyle = BRPickerStyle()
        customStyle.titleTextColor = hexColor(0x000000,0xBBBBBB)
        customStyle.titleTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneBorderStyle = .none
        customStyle.cancelBorderStyle = .none
        stringPickerView.pickerStyle = customStyle;
        return stringPickerView
    }
    
    
    //MARK:-时间显示：hh:mm
    static func showPickerModeYMD(title:String) -> BRDatePickerView {
        
        let  datePickerView = BRDatePickerView()
        datePickerView.pickerMode = .YMD;
        datePickerView.title = title;
        // 自定义弹框样式
        let customStyle = BRPickerStyle()
        customStyle.titleTextColor = hexColor(0x000000,0xBBBBBB)
        customStyle.titleTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneBorderStyle = .none
        customStyle.cancelBorderStyle = .none
        datePickerView.pickerStyle = customStyle;
        return datePickerView
    }
    //MARK:-地址选择
    static func showAddressPicker() -> BRAddressPickerView {
        
        let  addressPicker = BRAddressPickerView()
        addressPicker.title = "请选择地区";
        // 自定义弹框样式
        let customStyle = BRPickerStyle()
        customStyle.titleTextColor = hexColor(0x000000,0xBBBBBB)
        customStyle.titleTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextColor = hexColor(0x2C88FA,0x2C88FA)
        customStyle.cancelTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneTextFont = DIMENSION_FONT_OF_SIZE(16)
        customStyle.doneBorderStyle = .none
        customStyle.cancelBorderStyle = .none
        addressPicker.pickerStyle = customStyle;
        
        return addressPicker
    }
    //MARK:-两个按钮弹窗
    static  func alterDoubleCenterView(title:String,subTitle:String,okTitle:String,cancelTitle:String) -> WMZDialog {
        
        let diaLog =  Dialog()
        diaLog.wMessage = subTitle
        diaLog.wTitle = title
        diaLog.wType = DialogTypeNornal
        diaLog.wOKTitle = okTitle
        diaLog.wCancelTitle = cancelTitle
        diaLog.wMessageColor = hexColor(0x888888,0xBBBBBB)
        diaLog.wTitleColor = hexColor(0x000000,0xBBBBBB)
        diaLog.wOKColor = HexRGB(0x8CC56C)
        diaLog.wCancelColor = hexColor(0x000000,0xBBBBBB)
        diaLog.wTitleFont = 18
        diaLog.wMessageFont = 15
        diaLog.wMainBackColor = hexColor(0xFAF8EF,0x2B2A3A)
        return   diaLog
        
    }
    //MARK:-单个按钮弹窗
    static  func alterSingleCenterView(title:String,subTitle:String,okTitle:String) -> WMZDialog {
        
        let diaLog =  Dialog()
        diaLog.wMessage = subTitle
        diaLog.wTitle = title
        diaLog.wType = DialogTypeNornal
        diaLog.wMessageColor = hexColor(0x888888,0xBBBBBB)
        diaLog.wTitleColor = hexColor(0x000000,0xBBBBBB)
        diaLog.wOKColor = HexRGB(0x8CC56C)
        diaLog.wTitleFont = 18
        diaLog.wMessageFont = 15
        diaLog.wMainBackColor = hexColor(0xFAF8EF,0x2B2A3A)
        return   diaLog
        
    }
    
    //输入框
    static func alterRenameInputView(title:String,placeholde:String) -> WMZDialog {
        
        let diaLog =  Dialog()
        
        diaLog.wType = DialogTypeWrite
        diaLog.wTitle = title
        diaLog.wMessage = ""
        //默认内容
        diaLog.wOKTitle = "确定"
        diaLog.wCancelTitle = "取消"
        diaLog.wMessageColor = hexColor(0x888888,0xBBBBBB)
        diaLog.wTitleColor = hexColor(0x000000,0xBBBBBB)
        diaLog.wOKColor = HexRGB(0x8CC56C)
        diaLog.wCancelColor = hexColor(0x000000,0xBBBBBB)
        //提示文本
        diaLog.wPlaceholder = placeholde
        //编辑框最大行数 大于行数则滚动
        diaLog.wWirteTextMaxLine = 10
        //编辑框可输入的文本最大文本长度
        diaLog.wWirteTextMaxNum = 200
        //键盘类型
        diaLog.wWirteKeyBoardType = .default
        diaLog.wMainBackColor = hexColor(0xFAF8EF,0x2B2A3A)
        return   diaLog
    }
    
    //底部单选弹窗
   static func alterBootomSingleView(title:String,dataSource:[String]) -> WMZDialog {

        let diaLog =  Dialog()
        diaLog.wType = DialogTypeSheet
        diaLog.wTitle = title
        diaLog.wData = dataSource
        return  diaLog
    }
     //自定义中间弹窗
    static func customView() -> WMZDialog {

         let diaLog =  Dialog()
         diaLog.wType = DialogTypeMyView
         diaLog.wShowAnimation = AninatonZoomIn
         diaLog.wHideAnimation = AninatonZoomOut
         diaLog.wAnimationDurtion = 0.5
         diaLog.wDisappelSecond = 0.5
         return  diaLog
       
     }
    
    //自定义底部弹窗
       static func customBootomView() -> WMZDialog {
        
            let diaLog =  Dialog()
            diaLog.wType = DialogTypeCardPresent
            diaLog.wDisappelSecond = 0.1
            //关闭圆角 默认有圆角
            diaLog.wMainRadius = 0
            //开启则滑动到顶部继续滑动可关闭 default YES
            diaLog.wOpenScrollClose = true
            //开启侧滑 default YES
            diaLog.wLeftScrollClose = false
            //开启拖动 default YES
            diaLog.wOpenDragging = true
            //开启底部缩放 default YES
            diaLog.wScaleParentVC = false
            return  diaLog
          
        }
    
    
}

class ConfirmAlertView: UIView {
    
    // MARK: - UI Components
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = HexRGB(0x1E223D)
        view.layer.cornerRadius = 20
        view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        view.alpha = 0
        return view
    }()
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
        label.textColor = .white
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
    
    private let messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        label.textColor = HexRGB(0xA0A5C0)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
    
    private let cancelButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("取消", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.setTitleColor(HexRGB(0xA0A5C0), for: .normal)
        button.backgroundColor = HexRGB(0x252A45)
        button.layer.cornerRadius = 12
        return button
    }()
    
    private let confirmButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("确定", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = HexRGB(0x3d4466)
        button.layer.cornerRadius = 12
        return button
    }()
    
    private let contentStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 15
        stackView.alignment = .center
        return stackView
    }()
    
    // MARK: - Properties
    private var confirmAction: (() -> Void)?
    private var cancelAction: (() -> Void)?
    private static var currentAlertView: ConfirmAlertView?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupActions()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.4)
        
        addSubview(containerView)
        
        // Setup content stack
        contentStackView.addArrangedSubview(titleLabel)
        contentStackView.addArrangedSubview(messageLabel)
        
        contentStackView.addArrangedSubview(confirmButton)
        // Setup button stack
        contentStackView.addArrangedSubview(cancelButton)
      
        containerView.addSubview(contentStackView)
        
        // Layout
        containerView.translatesAutoresizingMaskIntoConstraints = false
        contentStackView.translatesAutoresizingMaskIntoConstraints = false
        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        confirmButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
    
            contentStackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 24),
            contentStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20),
            contentStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 24),
            contentStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -24),
            
            cancelButton.heightAnchor.constraint(equalToConstant: 44),
            cancelButton.leadingAnchor.constraint(equalTo: contentStackView.leadingAnchor, constant:0),
            cancelButton.trailingAnchor.constraint(equalTo: contentStackView.trailingAnchor, constant: 0),
            
            confirmButton.heightAnchor.constraint(equalToConstant: 44),
            confirmButton.leadingAnchor.constraint(equalTo: contentStackView.leadingAnchor, constant: 0),
            confirmButton.trailingAnchor.constraint(equalTo: contentStackView.trailingAnchor, constant: 0),
        ])
    }
    
    private func setupActions() {
        cancelButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
    }
    
    // MARK: - Button Actions
    @objc private func cancelButtonTapped() {
        hide {
            self.cancelAction?()
        }
    }
    
    @objc private func confirmButtonTapped() {
        hide {
            self.confirmAction?()
        }
    }
    
    // MARK: - Public Methods
    static func show(
        title: String,
        message: String? = nil,
        confirmTitle: String = "confirm".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        // Hide previous alert if exists
        hide()
        
        guard let window = getKeyWindow() else { return }
        
        let alertView = ConfirmAlertView()
        alertView.titleLabel.text = title
        alertView.messageLabel.text = message
        alertView.messageLabel.isHidden = message == nil
        
        alertView.confirmButton.setTitle(confirmTitle, for: .normal)
        alertView.cancelButton.setTitle(cancelTitle, for: .normal)
        
        alertView.confirmAction = confirmAction
        alertView.cancelAction = cancelAction
        
        alertView.frame = window.bounds
        window.addSubview(alertView)
        
        currentAlertView = alertView
        
        // Animate appearance
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5) {
            alertView.containerView.alpha = 1
            alertView.containerView.transform = .identity
        }
    }
    
    static func hide(completion: (() -> Void)? = nil) {
        guard let alertView = currentAlertView else {
            completion?()
            return
        }
        
        UIView.animate(withDuration: 0.2, animations: {
            alertView.containerView.alpha = 0
            alertView.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        }) { _ in
            alertView.removeFromSuperview()
            currentAlertView = nil
            completion?()
        }
    }
    
    // MARK: - Private Methods
    private func hide(completion: (() -> Void)? = nil) {
        ConfirmAlertView.hide(completion: completion)
    }
    
    private static func getKeyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .foregroundActive }
                .compactMap { $0 as? UIWindowScene }
                .first?.windows
                .filter { $0.isKeyWindow }.first
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}


// MARK: - 扩展样式变体
extension ConfirmAlertView {
    
    // 危险操作样式（红色确认按钮）
    static func showDangerAlert(
        title: String,
        message: String? = nil,
        confirmTitle: String = "delete".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        show(
            title: title,
            message: message,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        ) {
            // 自定义危险样式
            if let alertView = currentAlertView {
                alertView.confirmButton.backgroundColor = .systemRed
                alertView.confirmButton.setTitleColor(.white, for: .normal)
            }
        }
    }
    
    // 单按钮样式（只有确定按钮）
    static func showSingleButtonAlert(
        title: String,
        message: String? = nil,
        buttonTitle: String = "confirm".localized,
        buttonAction: (() -> Void)? = nil
    ) {
        show(
            title: title,
            message: message,
            confirmTitle: buttonTitle,
            cancelTitle: "",
            confirmAction: buttonAction,
            cancelAction: nil
        ) {
            if let alertView = currentAlertView {
                alertView.cancelButton.isHidden = true
                alertView.contentStackView.distribution = .fill
            }
        }
    }
    
    // 带图标的弹窗
    static func showWithIcon(
        title: String,
        message: String? = nil,
        icon: UIImage?,
        confirmTitle: String = "confirm".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        show(
            title: title,
            message: message,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        ) {
            if let alertView = currentAlertView, let icon = icon {
                let imageView = UIImageView(image: icon)
                imageView.contentMode = .scaleAspectFit
                imageView.tintColor = .systemBlue
                imageView.translatesAutoresizingMaskIntoConstraints = false
                imageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
                
                // 插入到标题上方
                alertView.contentStackView.insertArrangedSubview(imageView, at: 0)
            }
        }
    }
    
    // 私有方法：显示后自定义
    private static func show(
        title: String,
        message: String? = nil,
        confirmTitle: String = "confirm".localized,
        cancelTitle: String = "cencel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil,
        customization: (() -> Void)? = nil
    ) {
        show(
            title: title,
            message: message,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        )
        
        // 执行自定义样式
        customization?()
    }
}

// MARK: - 弹窗管理器
class AlertManager {
    static let shared = AlertManager()
    
    private init() {}
    
    // 基础确认弹窗
    func showConfirm(
        title: String,
        message: String? = nil,
        confirmTitle: String = "confirm".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        ConfirmAlertView.show(
            title: title,
            message: message,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        )
    }
    
    // 危险操作弹窗
    func showDangerConfirm(
        title: String,
        message: String? = nil,
        confirmTitle: String = "delete".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        ConfirmAlertView.showDangerAlert(
            title: title,
            message: message,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        )
    }
    
    // 单按钮提示弹窗
    func showAlert(
        title: String,
        message: String? = nil,
        buttonTitle: String = "confirm".localized,
        buttonAction: (() -> Void)? = nil
    ) {
        ConfirmAlertView.showSingleButtonAlert(
            title: title,
            message: message,
            buttonTitle: buttonTitle,
            buttonAction: buttonAction
        )
    }
    
    // 带图标的弹窗
    func showIconAlert(
        title: String,
        message: String? = nil,
        icon: UIImage?,
        confirmTitle: String = "confirm".localized,
        cancelTitle: String = "cancel".localized,
        confirmAction: (() -> Void)? = nil,
        cancelAction: (() -> Void)? = nil
    ) {
        ConfirmAlertView.showWithIcon(
            title: title,
            message: message,
            icon: icon,
            confirmTitle: confirmTitle,
            cancelTitle: cancelTitle,
            confirmAction: confirmAction,
            cancelAction: cancelAction
        )
    }
    
    // 隐藏所有弹窗
    func hideAllAlerts() {
        ConfirmAlertView.hide()
    }
}

class ElegantLoadingView: UIView {
    
    // MARK: - UI Components
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor =  HexRGB(0x1E223D)
        view.layer.cornerRadius = 16
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.layer.shadowRadius = 12
        view.layer.shadowOpacity = 0.15
        view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        view.alpha = 0
        return view
    }()
    
    private let activityIndicator: UIActivityIndicatorView = {
        var indicator:UIActivityIndicatorView!
        if #available(iOS 13.0, *) {
            indicator = UIActivityIndicatorView(style: .large)
        } else {
            indicator =  UIActivityIndicatorView(style: .whiteLarge)
        }
        indicator.color = .white
        return indicator
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.textColor = .white
        label.textAlignment = .center
        label.numberOfLines = 0
        label.text = "loadingTitle".localized
        return label
    }()
    
    private let messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = HexRGB(0xA0A5C0)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
    
    
    // MARK: - Properties
    private static var currentLoadingView: ElegantLoadingView?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.3)
   
        addSubview(containerView)
        
        let stackView = UIStackView(arrangedSubviews: [activityIndicator, titleLabel, messageLabel])
        stackView.axis = .vertical
        stackView.spacing = 30
        stackView.alignment = .center
        
        containerView.addSubview(stackView)
        
        // Layout
        containerView.translatesAutoresizingMaskIntoConstraints = false
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
            
            stackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 24),
            stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -24),
            stackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            stackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20)
        ])
    }
    
    // MARK: - Public Methods
    static func show(title: String = "loadingTitle".localized, message: String? = nil) {
        // Hide previous loading view if exists
        hide()
        
        guard let window = getKeyWindow() else { return }
        
        let loadingView = ElegantLoadingView()
        loadingView.titleLabel.text = title
        loadingView.messageLabel.text = message
        loadingView.messageLabel.isHidden = message == nil
        
        loadingView.frame = window.bounds
        window.addSubview(loadingView)
        
        loadingView.activityIndicator.startAnimating()
        currentLoadingView = loadingView
        
        // Animate appearance
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5) {
            loadingView.containerView.alpha = 1
            loadingView.containerView.transform = CGAffineTransform.identity
        }
    }
    
    static func hide(completion: (() -> Void)? = nil) {
        guard let loadingView = currentLoadingView else {
            completion?()
            return
        }
  
        UIView.animate(withDuration: 0.2, animations: {
            loadingView.containerView.alpha = 0
            loadingView.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        }) { _ in
            loadingView.activityIndicator.stopAnimating()
            loadingView.removeFromSuperview()
            currentLoadingView = nil
            completion?()
        }
    }
    
    static func updateMessage(_ message: String) {
        currentLoadingView?.messageLabel.text = message
        currentLoadingView?.messageLabel.isHidden = false
    }
    static func updateTitle(_ title: String) {
        currentLoadingView?.titleLabel.text = title
    }
    
    // MARK: - Helper Methods
    private static func getKeyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .foregroundActive }
                .compactMap { $0 as? UIWindowScene }
                .first?.windows
                .filter { $0.isKeyWindow }.first
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}
class ProgressLoadingView: UIView {
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = HexRGB(0x1E223D)
        view.layer.cornerRadius = 20
        view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        view.alpha = 0
        return view
    }()
    
    private let progressView: UIProgressView = {
        let progress = UIProgressView(progressViewStyle: .bar)
        progress.progressTintColor = .systemBlue
        progress.trackTintColor = .white
        progress.layer.cornerRadius = 2
        progress.clipsToBounds = true
        progress.transform = CGAffineTransform(scaleX: 1, y: 2)
        return progress
    }()
    
    private let percentageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.monospacedDigitSystemFont(ofSize: 16, weight: .medium)
        label.textColor = HexRGB(0xA0A5C0)
        label.textAlignment = .center
        label.text = "0%"
        return label
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.textColor = .white
        label.textAlignment = .center
        return label
    }()
    
    private let circularProgressLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.strokeColor = UIColor.systemBlue.cgColor
        layer.fillColor = UIColor.clear.cgColor
        layer.lineWidth = 4
        layer.lineCap = CAShapeLayerLineCap.round
        layer.strokeEnd = 0
        return layer
    }()
    
    // MARK: - Properties
    private static var currentProgressView: ProgressLoadingView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        addSubview(containerView)
        
        let circularView = UIView()
        circularView.layer.addSublayer(circularProgressLayer)
        
        let stackView = UIStackView(arrangedSubviews: [circularView, titleLabel, progressView, percentageLabel])
        stackView.axis = .vertical
        stackView.spacing = 16
        stackView.alignment = .center
        
        containerView.addSubview(stackView)
        
        // Layout
        containerView.translatesAutoresizingMaskIntoConstraints = false
        stackView.translatesAutoresizingMaskIntoConstraints = false
        circularView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
       
            circularView.widthAnchor.constraint(equalToConstant: 60),
            circularView.heightAnchor.constraint(equalToConstant: 60),
            
            progressView.widthAnchor.constraint(equalTo: stackView.widthAnchor),
            
            stackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 24),
            stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -24),
            stackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            stackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20)
        ])
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // Update circular progress path
        let circularPath = UIBezierPath(
            arcCenter: CGPoint(x: 30, y: 30),
            radius: 25,
            startAngle: -CGFloat.pi / 2,
            endAngle: 3 * CGFloat.pi / 2,
            clockwise: true
        )
        circularProgressLayer.path = circularPath.cgPath
    }
    
    // MARK: - Public Methods
    static func show(title: String = "loadingTitle".localized) {
        // Hide previous progress view if exists
        hide()
        
        guard let window = getKeyWindow() else { return }
        
        let progressView = ProgressLoadingView()
        progressView.titleLabel.text = title
        progressView.frame = window.bounds
        window.addSubview(progressView)
        
        currentProgressView = progressView
        
        // Animate appearance
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5) {
            progressView.containerView.alpha = 1
            progressView.containerView.transform = .identity
        }
    }
    
    static func updateProgress(_ progress: Float, animated: Bool = true) {
        guard let progressView = currentProgressView else { return }
        
        let percentage = Int(progress * 100)
        progressView.percentageLabel.text = "\(percentage)%"
        
        if animated {
            UIView.animate(withDuration: 0.3) {
                progressView.progressView.setProgress(progress, animated: true)
            }
            
            let animation = CABasicAnimation(keyPath: "strokeEnd")
            animation.toValue = progress
            animation.duration = 0.3
            animation.fillMode = CAMediaTimingFillMode.backwards
            animation.isRemovedOnCompletion = false
            progressView.circularProgressLayer.add(animation, forKey: "progress")
        } else {
            progressView.progressView.progress = progress
            progressView.circularProgressLayer.strokeEnd = CGFloat(progress)
        }
    }
    
    static func hide() {
        guard let progressView = currentProgressView else { return }
        
        UIView.animate(withDuration: 0.2, animations: {
            progressView.containerView.alpha = 0
            progressView.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        }) { _ in
            progressView.removeFromSuperview()
            currentProgressView = nil
        }
    }
    
    // MARK: - Helper Methods
    private static func getKeyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .foregroundActive }
                .compactMap { $0 as? UIWindowScene }
                .first?.windows
                .filter { $0.isKeyWindow }.first
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}
class LoadingManager {
    static let shared = LoadingManager()
    
    private init() {}
    
    // MARK: - Basic Loading
    func showLoading(title: String = "loadingTitle".localized, message: String? = nil) {
        ElegantLoadingView.show(title: title, message: message)
    }
    
    func hideLoading(completion: (() -> Void)? = nil) {
        ElegantLoadingView.hide(completion: completion)
    }
    
    func updateLoadingMessage(_ message: String) {
        ElegantLoadingView.updateMessage(message)
    }
    
    func updateLoadingTitle(_ title: String) {
        ElegantLoadingView.updateTitle(title)
    }
    
    // MARK: - Progress Loading
    func showProgressLoading(title: String = "loadingTitle".localized) {
        ProgressLoadingView.show(title: title)
    }
    
    func updateProgress(_ progress: Float, animated: Bool = true) {
        ProgressLoadingView.updateProgress(progress, animated: animated)
    }
    
    func hideProgressLoading() {
        ProgressLoadingView.hide()
    }
    // MARK: - Auto Hide with Delay
    func showSuccess(message: String = "操作成功", delay: TimeInterval = 1.5) {
        ElegantLoadingView.show(title: "成功", message: message)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            self.hideLoading()
        }
    }
    func showError(message: String = "操作失败", delay: TimeInterval = 1.5) {
        ElegantLoadingView.show(title: "错误", message: message)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            self.hideLoading()
        }
    }
}

/**
     漂亮的进度条
 */


class CircularProgressView: UIView {
    
    // MARK: - 属性
    
    /// 进度值 (0.0 - 1.0)
    public var progress: CGFloat = 0.0 {
        didSet {
            progress = min(max(progress, 0.0), 1.0)
            updateProgress()
        }
    }
    
    /// 标题
    public var title: String = "进度" {
        didSet {
            titleLabel.text = title
        }
    }
    
    /// 描述
    public var descriptionText: String = "任务进行中..." {
        didSet {
            descriptionLabel.text = descriptionText
        }
    }
    
    /// 圆环线宽
    public var lineWidth: CGFloat = 8.0 {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 进度条颜色
    public var progressColor: UIColor = UIColor.systemBlue {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 背景圆环颜色
    public var trackColor: UIColor = UIColor.gray {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 标题颜色
    public var titleColor: UIColor = UIColor.black {
        didSet {
            titleLabel.textColor = titleColor
        }
    }
    
    /// 描述颜色
    public var descriptionColor: UIColor = UIColor.darkGray {
        didSet {
            descriptionLabel.textColor = descriptionColor
        }
    }
    
    /// 进度数值颜色
    public var progressTextColor: UIColor = UIColor.red {
        didSet {
            progressLabel.textColor = progressTextColor
        }
    }
    
    /// 进度数值字体
    public var progressFont: UIFont = UIFont.systemFont(ofSize: 24, weight: .bold) {
        didSet {
            progressLabel.font = progressFont
        }
    }
    
    /// 标题字体
    public var titleFont: UIFont = UIFont.systemFont(ofSize: 18, weight: .semibold) {
        didSet {
            titleLabel.font = titleFont
        }
    }
    
    /// 描述字体
    public var descriptionFont: UIFont = UIFont.systemFont(ofSize: 14, weight: .regular) {
        didSet {
            descriptionLabel.font = descriptionFont
        }
    }
    
    // MARK: - UI组件
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        label.textColor = .black
        return label
    }()
    
    private let descriptionLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = .darkGray
        label.numberOfLines = 0
        return label
    }()
    
    private let progressLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 24, weight: .bold)
        label.textColor = .darkGray
        label.text = "0%"
        return label
    }()
    
    private let progressLayer = CAShapeLayer()
    private let trackLayer = CAShapeLayer()
    
    // MARK: - 初始化
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI设置
    
    private func setupUI() {
        backgroundColor = .clear
        
        // 添加子视图
        addSubview(titleLabel)
        addSubview(descriptionLabel)
        addSubview(progressLabel)
        
        // 设置图层
        layer.addSublayer(trackLayer)
        layer.addSublayer(progressLayer)
        
        // 设置图层属性
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.strokeColor = trackColor.cgColor
        trackLayer.lineWidth = lineWidth
        trackLayer.lineCap = .round
        
        progressLayer.fillColor = UIColor.clear.cgColor
        progressLayer.strokeColor = progressColor.cgColor
        progressLayer.lineWidth = lineWidth
        progressLayer.lineCap = .round
        progressLayer.strokeEnd = 0.0
        
        // 设置初始值
        titleLabel.text = title
        descriptionLabel.text = descriptionText
    }
    
    // MARK: - 布局
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let padding: CGFloat = 16
        let progressViewHeight = min(bounds.width, bounds.height - 120)
        let progressViewY = (bounds.height - progressViewHeight) / 2
        
        // 标题布局
        titleLabel.frame = CGRect(x: padding, y: 8,
                                width: bounds.width - 2 * padding, height: 24)
        
        // 进度标签布局（居中）
        progressLabel.frame = CGRect(x: 0, y: progressViewY,
                                   width: bounds.width, height: progressViewHeight)
        
        // 描述布局
        descriptionLabel.frame = CGRect(x: padding, y: progressViewY + progressViewHeight + 8,
                                      width: bounds.width - 2 * padding, height: 40)
        
        // 更新圆环路径
        updateCircularPath()
    }
    
    // MARK: - 绘制圆环
    
    private func updateCircularPath() {
        let center = CGPoint(x: bounds.width / 2, y: progressLabel.center.y)
        let radius = min(bounds.width, progressLabel.bounds.height) / 2 - lineWidth / 2
        let startAngle = -CGFloat.pi / 2
        let endAngle = 3 * CGFloat.pi / 2
        
        let circularPath = UIBezierPath(arcCenter: center,
                                      radius: radius,
                                      startAngle: startAngle,
                                      endAngle: endAngle,
                                      clockwise: true)
        
        trackLayer.path = circularPath.cgPath
        progressLayer.path = circularPath.cgPath
    }
    
    // MARK: - 更新进度
    
    private func updateProgress() {
        // 更新进度标签
        let percentage = Int(progress * 100)
        progressLabel.text = "\(percentage)%"
        
        // 动画更新进度条
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = 0.5
        animation.fromValue = progressLayer.strokeEnd
        animation.toValue = progress
        animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        
        progressLayer.strokeEnd = progress
        progressLayer.add(animation, forKey: "progressAnimation")
    }
    
    // MARK: - 公共方法
    
    /// 设置进度（带动画）
    /// - Parameters:
    ///   - progress: 进度值 (0.0 - 1.0)
    ///   - animated: 是否动画
    ///   - duration: 动画时长
    public func setProgress(_ progress: CGFloat, animated: Bool = true, duration: TimeInterval = 0.5) {
        let newProgress = min(max(progress, 0.0), 1.0)
        
        if animated {
            let animation = CABasicAnimation(keyPath: "strokeEnd")
            animation.duration = duration
            animation.fromValue = self.progress
            animation.toValue = newProgress
            animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            
            progressLayer.strokeEnd = newProgress
            progressLayer.add(animation, forKey: "progressAnimation")
            
            // 更新数值标签（可以添加数值变化的动画）
            UIView.animate(withDuration: duration) {
                let percentage = Int(newProgress * 100)
                self.progressLabel.text = "\(percentage)%"
            }
        } else {
            progressLayer.strokeEnd = newProgress
            let percentage = Int(newProgress * 100)
            progressLabel.text = "\(percentage)%"
        }
        
        self.progress = newProgress
    }
    
    /// 重置进度
    public func resetProgress() {
        setProgress(0.0, animated: false)
    }
    
    /// 显示完成状态
    public func showCompleted() {
        setProgress(1.0, animated: true)
        descriptionText = "任务完成！"
    }
}
// MARK: - 进度条弹窗管理器
class ProgressPopupManager {
    
    static let shared = ProgressPopupManager()
    
    private var popupView: ProgressPopupView?
    
    private init() {}
    
    /// 显示进度条弹窗
    /// - Parameters:
    ///   - title: 标题
    ///   - description: 描述
    ///   - progress: 初始进度 (0.0-1.0)
    @discardableResult
    func showProgressPopup(title: String = "进度",
                          description: String = "任务进行中...",
                          progress: CGFloat = 0.0) -> ProgressPopupView {
        
        // 先隐藏已存在的弹窗
        hideProgressPopup()
        
        let popupView = ProgressPopupView()
        popupView.title = title
        popupView.descriptionText = description
        popupView.setProgress(progress, animated: false)
        
        // 添加到窗口
        if let window = getKeyWindow() {
            popupView.frame = window.bounds
            window.addSubview(popupView)
            
            // 显示动画
            popupView.show()
        }
        
        self.popupView = popupView
        return popupView
    }
    
    /// 更新进度
    func updateProgress(_ progress: CGFloat, animated: Bool = true) {
        popupView?.setProgress(progress, animated: animated)
    }
    
    /// 更新标题和描述
    func updateTexts(title: String? = nil, description: String? = nil) {
        if let title = title {
            popupView?.title = title
        }
        if let description = description {
            popupView?.descriptionText = description
        }
    }
    
    /// 显示完成状态
    func showCompleted(completion: (() -> Void)? = nil) {
        popupView?.showCompleted(completion: completion)
    }
    
    /// 隐藏进度条弹窗
    func hideProgressPopup(completion: (() -> Void)? = nil) {
        popupView?.hide(completion: { [weak self] in
            self?.popupView = nil
            completion?()
        })
    }
    
    /// 获取关键窗口
    private func getKeyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .filter { $0.activationState == .foregroundActive }
                .compactMap { $0 as? UIWindowScene }
                .first?.windows
                .filter { $0.isKeyWindow }.first
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}

// MARK: - 进度条弹窗视图
class ProgressPopupView: UIView {
    
    // MARK: - 属性
    public var title: String = "进度" {
        didSet {
            progressView.title = title
        }
    }
    
    public var descriptionText: String = "任务进行中..." {
        didSet {
            progressView.descriptionText = descriptionText
        }
    }
    
    public var progress: CGFloat {
        return progressView.progress
    }
    
    /// 点击背景是否可关闭
    public var tapBackgroundToDismiss: Bool = false
    
    /// 弹窗显示/隐藏动画时长
    public var animationDuration: TimeInterval = 0.3
    
    // MARK: - UI组件
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        view.layer.cornerRadius = 16
        view.layer.masksToBounds = true
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 2)
        view.layer.shadowRadius = 8
        view.layer.shadowOpacity = 0.15
        return view
    }()
    
    private let progressView = CircularProgressView()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "xmark.circle.fill"), for: .normal)
        button.tintColor = .systemGray
        button.imageView?.contentMode = .scaleAspectFit
        return button
    }()
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupActions()
    }
    
    // MARK: - UI设置
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        // 添加子视图
        addSubview(containerView)
        containerView.addSubview(progressView)
        containerView.addSubview(closeButton)
        
        // 设置进度条样式
        progressView.progressColor = .systemBlue
        progressView.trackColor = .lightGray
        progressView.lineWidth = 10
        progressView.titleFont = UIFont.systemFont(ofSize: 20, weight: .semibold)
        progressView.progressFont = UIFont.systemFont(ofSize: 28, weight: .bold)
        
        setupConstraints()
    }
    
    private func setupConstraints() {
        containerView.translatesAutoresizingMaskIntoConstraints = false
        progressView.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // 容器视图约束
            containerView.centerXAnchor.constraint(equalTo: centerXAnchor),
            containerView.centerYAnchor.constraint(equalTo: centerYAnchor),
            containerView.widthAnchor.constraint(equalToConstant: 280),
            containerView.heightAnchor.constraint(equalToConstant: 320),
            
            // 关闭按钮约束
            closeButton.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 12),
            closeButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -12),
            closeButton.widthAnchor.constraint(equalToConstant: 30),
            closeButton.heightAnchor.constraint(equalToConstant: 30),
            
            // 进度条视图约束
            progressView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20),
            progressView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20),
            progressView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20),
            progressView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20)
        ])
    }
    
    private func setupActions() {
        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        
        // 添加背景点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
        tapGesture.delegate = self
        addGestureRecognizer(tapGesture)
    }
    
    // MARK: - 动作处理
    @objc private func closeButtonTapped() {
        hide()
    }
    
    @objc private func backgroundTapped(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: self)
        if !containerView.frame.contains(location) && tapBackgroundToDismiss {
            hide()
        }
    }
    
    // MARK: - 公共方法
    public func setProgress(_ progress: CGFloat, animated: Bool = true) {
        progressView.setProgress(progress, animated: animated)
    }
    
    public func showCompleted(completion: (() -> Void)? = nil) {
        progressView.showCompleted()
        
        // 延迟一段时间后自动隐藏
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.hide(completion: completion)
        }
    }
    
    public func show() {
        // 初始状态
        alpha = 0
        containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        
        // 显示动画
        UIView.animate(withDuration: animationDuration,
                      delay: 0,
                      usingSpringWithDamping: 0.7,
                      initialSpringVelocity: 0.5,
                      options: .curveEaseOut) {
            self.alpha = 1
            self.containerView.transform = .identity
        }
    }
    
    public func hide(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: animationDuration,
                      delay: 0,
                      options: .curveEaseIn) {
            self.alpha = 0
            self.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        } completion: { _ in
            self.removeFromSuperview()
            completion?()
        }
    }
}

// MARK: - 手势代理
extension ProgressPopupView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let location = touch.location(in: self)
        return !containerView.frame.contains(location)
    }
}




